// Copyright 2019 The rhyme_lph Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// h [author] rhyme_lph
// M [email]  rhymelph@gmail.com
// g [github] https://github.com/rhymelph

import 'package:base_plugin/base_plugin.dart';
import 'package:finance_app/src/entities/contact_person_entity.dart';
import 'package:finance_app/src/http_service/http_contact_person_service.dart';
import 'package:finance_app/src/mixin/search_data_list_mixin.dart';
import 'package:finance_app/src/provider/dashboard/contact/business_contact_detail_provider.dart';
import 'package:finance_app/src/router_gen/router_gen_providers.dart';

class ContactDetailPersonProvider
    extends BaseProvider<List<ContactPersonEntity>> with SearchDataListMixin {
  int get contactId => getParentProvider<BusinessContactDetailProvider>().id;

  @override
  Future get dataFuture => HttpContactPersonService.contactList(contactId);

  @override
  void searchRefreshData(data) {
    update();
  }

  void onNavContactPerson(ContactPersonEntity value) async {
    unFocus();
    await Routes.navigateTo(RouterGenProviders.newContactPersonPage,
        params: {'data': value});
  }

  @override
  FutureOr<List<ContactPersonEntity>> transformData(
      List<ContactPersonEntity> d, bool isCache) {
    d.sort((a, b) {
      if (a.isPrimary == 1 && b.isPrimary == 1) {
        return a.name.compareTo(b.name);
      }
      if (a.isPrimary == 1) return 0;
      if (b.isPrimary == 1) return 1;
      return a.name.compareTo(b.name);
    });
    return super.transformData(d, isCache);
  }

  void onDeleteContact(int id) {
    data.removeWhere((element) => element.id == id);
    data = transformData(data, false);
    update();
  }

  void onUpdateContact(ContactPersonEntity entity) {
    final finder = data.firstWhere((element) => element.id == entity.id,
        orElse: () => null);
    if (finder != null) {
      finder.fromJson(entity.toJson());
    } else {
      data.add(entity);
    }
    data = transformData(data, false);
    update();
  }
}
